/*
 * Copyright © 2022 XXXXXXXXX
 * @Author: zhangxiang
 * @Date: 2022-07-25 15:21:57
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-11-04 10:10:29
 * @Description:
 *
 */

import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 60 * 1000, // request timeout
  headers: { 'X-Requested-With': 'XMLHttpRequest' }
})
// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    // let each request carry token
    config.headers['Authorization'] = getToken()
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    return response
  },
  (error) => {
    // 取消请求的error 跳过异常处理
    if (axios.isCancel(error)) {
      return Promise.reject(error)
    }
    console.log(error)
    if (error && error.response) {
      switch (error.response.status) {
        case 401:
          // 未登录拦截
          Message({
            message: '登录状态已失效，请重新登录。',
            type: 'error',
            duration: 3 * 1000
          })
          // 重置用户
          store.dispatch('user/resetState').finally(() => {
            // 去登录
            router.replace({
              path: `/login?redirect=${location.hash.replace('#', '')}`
            })
          })
          return Promise.reject(error)
        default:
          Message({
            message: error.message,
            type: 'error',
            duration: 3 * 1000
          })
          return Promise.reject(error)
      }
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

/**
 * 文件下载专用接口
 * @param {*} url
 * @param {*} data
 */
export function downLoadFile(url) {
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        headers: {
          'Content-Type': 'application/json;application/octet-stream'
        },
        responseType: 'blob'
      })
      .then(
        (response) => {
          resolve([response.data, response.headers['filename']])
        },
        (err) => {
          reject(err)
        }
      )
  })
}

/**
 * @description: GET请求
 * @param {*} url
 * @param {*} paramsOrData
 * @return {*}
 */
export function GET(url, paramsOrData) {
  return service({ method: 'GET', url, params: paramsOrData })
}

/**
 * @description: POST请求
 * @param {*} url
 * @param {*} paramsOrData
 * @param {*} headers
 * @return {*}
 */
export function POST(url, paramsOrData, headers) {
  if (headers) {
    return service({ method: 'POST', url, data: paramsOrData, headers })
  }
  return service({ method: 'POST', url, data: paramsOrData })
}

export default service
